/**
 * Created by Frank on 4/9/15.
 *
 * each category maintains a set of their tagRule
 * Map<Id,Array()>  : Id : SelectedNodeValue    Array(): LessonTime_TagId
 * the Id should be "CourseId_GradeId" while the selectedNodeType is "courseGrade"
 * @type {HashMap}
 */

var classTagRuleMap = new HashMap();
var gradeTagRuleMap = new HashMap();
var courseTagRuleMap = new HashMap();
var courseGradeTagRuleMap = new HashMap();
var teacherTagRuleMap = new HashMap();
var classFlag = false;
var teacherFlag = false;
var courseFlag = false;
var gradeFlag = false;
var gradeCourseFlag = false;
var courseGradeFlag = false
var fadeTime = 1000;

// type const
var CLASS = "class";
var GRADE = "grade";
var SUBJECT = "subject";
var COURSE = "course";
var COURSEGRADE = "courseGrade";
var TEACHER = "teacher";

var tagList = null;
var tagChanged = false;


/**
 * @param lessonTime
 * @param curTagId
 * @param curTagName
 * @constructor
 */
function Item(lessonTime, curTagId, curTagName) {
    this.timeIndex = lessonTime;
    this.tagId = curTagId;
    this.tagName = curTagName;

    var getId = function () {
        return tagId;
    }
    var getName = function () {
        return tagName;
    }
    var getTime = function () {
        return timeIndex;
    }
}
/**
 * load the tag rules while the document ready
 */
function getTagRuleMap() {

    jQuery.ajax({
        type: "GET",
        url: "/m/tagRule/getRule",
        data: { "taskId": taskId },
        dataType: "json",
        async: false,
        cache: false,
        success: function (msg) {
            if (msg) {
                for (var i = 0; i < msg.length; i++) {
                    var item = msg[i];
                    var tmp = new Item(item.lessonTime, item.tagId, item.tagName);
                    if (item.type == CLASS) {
                        parseToMap(classTagRuleMap, item.ownerId, tmp);
                    } else if (item.type == GRADE) {
                        parseToMap(gradeTagRuleMap, item.ownerId, tmp);
                    } else if (item.type == COURSE) {
                        parseToMap(courseTagRuleMap, item.ownerId, tmp);
                    } else if (item.type == COURSEGRADE) {
                        parseToMap(courseGradeTagRuleMap, item.ownerId, tmp);
                    } else if (item.type == TEACHER) {
                        parseToMap(teacherTagRuleMap, item.ownerId, tmp);
                    } else {
                        console.log(item.ownerId + " : " + item.tagId + " : " + item.tagName + " : " + item.type + " : " + item.lessonTime);
                    }
                }


            }
        }
    })
}
function parseToMap(map, key, value) {
    var arr = null;
    if (map.containsKey(key)) {
        arr = map.get(key);
        arr.push(value);
    } else {
        arr = new Array();
        arr.push(value);
        map.put(key, arr);
    }

}
function addTags() {
    $("#addTagsModal").modal('show');
}

function updateTags() {
    /**
     * javascript
     * show之前先填充updateTagsModal
     */
    getTags();
    if (tagList != null && tagList.length > 0) {
        var html = new Array();
        for (var index = 0; index < tagList.length; index++) {
            html.push("<tr id='tr_" + tagList[index].id + "'> <td>");
            html.push("<div class='input-group'>" +
                "<input type='text' class='form-control' placeholder='" + tagList[index].name + "'>" +
                "<span class='input-group-btn'>" +
                "<button class='btn btn-primary' type='button' onclick='updateTagName(" + tagList[index].id + ")'>更新" +
                "</button></span></div></td>");
            html.push("<td><button class='btn btn-link' type='button' onclick='removeTag(" + tagList[index].id + ")'>删除</button></td></tr>");
        }
        $("#updateTagInfos tbody").html(html.join(""));
    }
    $("#updateTagsModal").modal("show");
}

function updateTagName(tagId) {
    var button = $("#tr_" + tagId).find("button.btn-primary");
    $(button).addClass("disabled");
    var sel = $("#tr_" + tagId);
    var input = sel.find("input")[0];
    var originName = $(input).attr("placeholder");
    var inputName = trim($(input).val());
    if (!inputName) {
        tagUpdateResult("<span class='text-warning'>标签名不能为空</span>");
        $(input).focus();
        $(button).removeClass("disabled");
        return;
    }
    if (originName == inputName) {
        tagUpdateResult("<span class='text-warning'>标签名未变化</span>");
        $(button).removeClass("disabled");
        return;
    }
    if (jQuery.isNumeric(inputName)) {
        tagUpdateResult("<span class='text-warning'>请不要使用无意义的数字</span>");
        $(button).removeClass("disabled");
        return;
    }
    jQuery.ajax({
        url: "/m/tags",
        type: "POST",
        async: false,
        data: { "tagId": tagId, "tagName": inputName, "_method": "PUT" },
        success: function (ret) {
            console.log("update name request ... : " + ret);
            if (ret.code == 200) {
                tagChanged = true;
                $(input).attr("placeholder", inputName);
                tagUpdateResult("<span class='text-success'>编辑成功</span>");
            } else {
                tagUpdateResult("<span class='text-warning'>保存失败</span>")
            }
            $(button).removeClass("disabled");
        }
    });
}

function tagUpdateResult(msg) {
    $("#updateTagResult").html(msg).show().fadeOut(fadeTime);
}
function removeTag(tagId) {
    if (!confirm("确定删除？")) {
        return;
    }
    jQuery.ajax({
        url: "/m/tags",
        type: "POST",
        async: false,
        data: { "taskId": taskId, "tagId": tagId, "_method": "DELETE" },
        success: function (ret) {
            console.log("delete : " + ret);
            if (ret.code == 200) {
                console.log("delete success : " + ret);
                tagChanged = true;
                $("#tr_" + tagId).remove();
                tagUpdateResult("<span class='text-success'>删除成功</span>");
            } else {
                tagUpdateResult("<span class='text-danger'>删除失败</span>");
            }
        }
    })
}
/**
 * get tag info by the taskId
 */
function getTags() {
    jQuery.ajax({
        url: "/m/tags?taskId=" + taskId,
        type: "GET",
        async: false,
        success: function (ret) {
            if (ret.code == 200) {
                tagList = ret.data;
            }
        }
    })
}

function tagSubmit() {
    var tagName = trim($("#tagName").val());
    if (jQuery.isNumeric(tagName)) {
        tagTips("请不要使用无意义的数字", "text-warning");
        return;
    }
    if (tagName == "") {
        tagTips("请输入标签名", "text-warning");
        $("#tagName").focus();
        return;
    }
    jQuery.ajax({
        type: "POST",
        url: "/m/tags",
        data: { "taskId": taskId, "tagName": tagName },
        dataType: "json",
        success: function (msg) {  // tagId or -1
            if (msg) {
                tagTips("添加成功", "text-success");
                buildTag(msg, trim(tagName));
                $("#tagName").val("");
            } else {
                tagTips("添加失败", "text-danger");
            }
        }
    });
}

function tagTips(msg, style) {
    $("#addTagResult").html("<span class='" + style + "'>" + msg + "</span>").fadeIn();
    $("#addTagResult").html("<span class='" + style + "'>" + msg + "</span>").fadeOut(5000);
}

/**
 * create the tag button
 * @param tagId
 * @param tagName
 */
function buildTag(tagId, tagName) {
    var button = "<li><button id='" + tagId + "' type='button' class='btn btn-default btn-md'>" + tagName + "</button></li>";
    $("#tagArea").append(button);
}
function contains(array, key) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].timeIndex == key) {
            return array[i]
        }
    }
    return null;
}
function put(array, item) {
    var ret = contains(array, item.timeIndex);
    if (ret != null) {
        array.remove(ret);
    }
    array.push(item);
}
/**
 *  isUnSchedule == false : remove record , based on lessonTime
 *  isUnSchedule == true : add record
 */
function setGradeTagRule(gradeId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var gradeTagArr = gradeTagRuleMap.get(gradeId);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);
    var item = new Item(timeIndex, currentTagId, currentTagName);
    if (gradeTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            gradeTagArr = new Array();
            gradeTagArr.push(item);
            gradeTagRuleMap.put(gradeId, gradeTagArr);
            gradeFlag = true;
        }
    } else {
        if (isUnSchedule == true && currentTagId != "") {
            // 这里不管包不包含都需要push
            put(gradeTagArr, item);
            gradeFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(gradeTagArr, timeIndex);
            if (tmp != null) {
                gradeTagArr.remove(tmp);
                gradeFlag = true;
            }
        }
    }
}

function setGradeCourseTagRule(gradeId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var gradeTagArr = gradeTagRuleMap.get(gradeId);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);
    var item = new Item(timeIndex, currentTagId, currentTagName);
    if (gradeTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            gradeTagArr = new Array();
            gradeTagArr.push(item);
            gradeTagRuleMap.put(gradeId, gradeTagArr);
            gradeCourseFlag = true;
        }
    } else {
        if (isUnSchedule == true && currentTagId != "") {
            // 这里不管包不包含都需要push
            put(gradeTagArr, item);
            gradeCourseFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(gradeTagArr, timeIndex);
            if (tmp != null) {
                gradeTagArr.remove(tmp);
                gradeCourseFlag = true;
            }
        }
    }
}

/**
 * cache the class tag rule
 * @param classId
 * @param timeIndex
 * @param isUnSchedule
 * @param currentTagId
 * @param currentTagName
 */
function setClassTagRule(classId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var classTagArr = classTagRuleMap.get(classId);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);

    var item = new Item(timeIndex, currentTagId, currentTagName);
    if (classTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            classTagArr = new Array();
            classTagArr.push(item);
            classTagRuleMap.put(classId, classTagArr);
            classFlag = true;
        }
    } else {
        if (isUnSchedule == true && currentTagId != "") {
            put(classTagArr, item);
            classFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(classTagArr, timeIndex);
            if (tmp != null) {
                classTagArr.remove(tmp);
                classFlag = true;
            }
        }

    }
}
/**
 * cache the course tag rule
 * @param courseId
 * @param timeIndex
 * @param isUnSchedule
 * @param currentTagId
 * @param currentTagName
 */
function setCourseTagRule(courseId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var courseTagArr = courseTagRuleMap.get(courseId);
    var item = new Item(timeIndex, currentTagId, currentTagName);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);

    if (courseTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            courseTagArr = new Array();
            courseTagArr.push(item);
            courseTagRuleMap.put(courseId, courseTagArr);
            courseFlag = true;
        }
    } else {
        if (isUnSchedule == true && currentTagId != "") {
            put(courseTagArr, item);
            courseFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(courseTagArr, timeIndex);
            if (tmp != null) {
                courseTagArr.remove(tmp);
                courseFlag = true;
            }
        }

    }
}
/**
 * cache the teacher tag rule
 * @param teacherId
 * @param timeIndex
 * @param isUnSchedule
 * @param currentTagId
 * @param currentTagName
 */
function setTeacherTagRule(teacherId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var teacherTagArr = teacherTagRuleMap.get(teacherId);
    var item = new Item(timeIndex, currentTagId, currentTagName);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);

    if (teacherTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            teacherTagArr = new Array();
            teacherTagArr.push(item);
            teacherTagRuleMap.put(teacherId, teacherTagArr);
            teacherFlag = true;
        }
    } else {

        if (isUnSchedule == true && currentTagId != "") {
            put(teacherTagArr, item);
            teacherFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(teacherTagArr, timeIndex);
            if (tmp != null) {
                teacherTagArr.remove(tmp);
                teacherFlag = true;
            }
        }
    }
}
/**
 * cache the courseGrade tag rule
 *
 * @param CourseIdAndGradeId
 * @param timeIndex
 * @param isUnSchedule
 * @param currentTagId
 * @param currentTagName
 */
function setCourseGradeTagRule(CourseIdAndGradeId, timeIndex, isUnSchedule, currentTagId, currentTagName) {
    var courseGradeTagArr = courseGradeTagRuleMap.get(CourseIdAndGradeId);
    var item = new Item(timeIndex, currentTagId, currentTagName);
    //console.log(gradeId + " : " + timeIndex + " : " + isUnSchedule +" : " +currentTagId + " : " +currentTagName);

    if (courseGradeTagArr == null) {
        if (isUnSchedule == true && currentTagId != "") {
            courseGradeTagArr = new Array();
            courseGradeTagArr.push(item);
            courseGradeTagRuleMap.put(CourseIdAndGradeId, courseGradeTagArr);
            courseGradeFlag = true;
        }
    } else {

        if (isUnSchedule == true && currentTagId != "") {
            put(courseGradeTagArr, item);
            courseGradeFlag = true;
        } else if (isUnSchedule == false) {
            var tmp = contains(courseGradeTagArr, timeIndex);
            if (tmp != null) {
                courseGradeTagArr.remove(tmp);
                courseGradeFlag = true;
            }
        }
    }
}
/**
 * save the changed data
 * change the changed flag into false after saved the changed data successfully
 * TODO: post the changed data to webPortal
 */

function saveTagRule(type) {
    var postData = "";
    var res = "";
    var msg = "";
    if (type == CLASS) {
        if (classFlag == true) {
            res = toString(classTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": CLASS, "json": res };
            msg = submit(postData);
            classFlag = msg ? false : true;
        }
        if (gradeFlag == true) {
            res = toString(gradeTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": GRADE, "json": res };
            msg = submit(postData);
            gradeFlag = msg ? false : true;
        }

    } else if (type == COURSE) {
        if (courseFlag == true) {
            res = toString(courseTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": COURSE, "json": res };
            msg = submit(postData);
            courseFlag = msg ? false : true;
        }
        if (courseGradeFlag == true) {
            res = toString(courseGradeTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": COURSEGRADE, "json": res };
            msg = submit(postData);
            courseGradeFlag = msg ? false : true;
        }
        if (gradeCourseFlag == true) {
            res = toString(gradeTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": GRADE, "json": res };
            msg = submit(postData);
            gradeCourseFlag = msg ? false : true;
        }
    } else { //teacher
        if (teacherFlag == true) {
            res = toString(teacherTagRuleMap, type);
            postData = { "taskId": taskId, "unScheduleType": TEACHER, "json": res };
            msg = submit(postData);
            teacherFlag = msg ? false : true;
        }
    }
    return msg;
}

/**
 * submit the postData
 * @param data
 * @returns {boolean}
 */
function submit(data) {
    var msg = false;
    jQuery.ajax({
        type: "POST",
        url: "/m/tagRule/updateRule",
        async: false,
        data: data,
        dataType: "json",
        success: function () {
            msg = true;
        }
    });
    return msg;
}
/**
 * create the post data
 * map<id,List<String>> : String : lessonTime_tagId
 * @param map
 */
function toString(map, type) {
    var array = new Array();
    if (map) {
        var keys = map.keySet();
        for (var i = 0; i < keys.length; i++) {
            var valueArr = map.get(keys[i]);
            if (valueArr) {
                for (var index = 0; index < valueArr.length; index++) {
                    var rule = {};
                    rule.ownerId = keys[i];
                    rule.type = type;
                    rule.lessonTime = valueArr[index].timeIndex;
                    rule.tagId = valueArr[index].tagId;
                    rule.tagName = valueArr[index].tagName;
                    array.push(rule);
                }
            }
        }
    }

    return JSON.stringify(array);
}

/** display the tag name on the table */
/**
 * just change the text of the td indicated by the lessonTime
 * @param gradeId
 */
function getGradeTagById(gradeId) {
    var gradeTimeArr = gradeTagRuleMap.get(gradeId);
    setTagName(gradeTimeArr);
    //if(gradeTimeArr != null){
    //    var length = gradeTimeArr.length;
    //    for(var i = 0; i< length;i++){
    //        $("#td_"+gradeTimeArr[i].timeIndex).html(gradeTimeArr[i].tagName);
    //    }
    //}
}

function getClassTagById(classId) {
    var classTimeArr = classTagRuleMap.get(classId);
    setTagName(classTimeArr);
    //if(classTimeArr != null){
    //    var length = classTimeArr.length;
    //    for(var i = 0; i< length; i++){
    //        $("#td_"+classTimeArr[i].timeIndex).html(classTimeArr[i].tagName);
    //
    //    }
    //}
}

function getCourseTagById(courseId) {
    var courseTimeArr = courseTagRuleMap.get(courseId);
    setTagName(courseTimeArr);
    //if(courseTimeArr != null){
    //    var length = courseTimeArr.length;
    //    for(var i = 0; i< length; i++){
    //        $("#td_"+courseTimeArr[i].timeIndex).html(courseTimeArr[i].tagName);
    //
    //    }
    //}
}

function getTeacherTagById(teacherId) {
    var teacherTimeArr = teacherTagRuleMap.get(teacherId);
    setTagName(teacherTimeArr);

    //if(teacherTimeArr != null){
    //    var length = teacherTimeArr.length;
    //    for(var i = 0; i< length; i++){
    //        $("#td_"+teacherTimeArr[i].timeIndex).html(teacherTimeArr[i].tagName);
    //
    //    }
    //}
}

function getCourseGradeTagById(courseId, gradeId) {
    var courseGradeTimeArr = courseGradeTagRuleMap.get(courseId + "_" + gradeId);
    setTagName(courseGradeTimeArr);
    //if(courseGradeTimeArr != null){
    //    var length = courseGradeTimeArr.length;
    //    for(var i = 0; i< length; i++){
    //        $("#td_"+courseGradeTimeArr[i].timeIndex).html(courseGradeTimeArr[i].tagName);
    //
    //    }
    //}
}

/**
 * 设置tagName
 * @param tagArr
 */
function setTagName(tagArr) {
    if (tagArr != null) {
        var length = tagArr.length;
        for (var i = 0; i < length; i++) {
            var c = $("#td_" + tagArr[i].timeIndex);
            if (trim(c.text()) != "") {
                $("#td_" + tagArr[i].timeIndex).html(tagArr[i].tagName);
            }
        }
    }
}

function clearTagInfo() {
    selectedTagId = "";
    selectedTagName = "";
    //清除tag
    $("#tagArea button").removeClass("btn-primary");
}